import numpy as np
import cv2
from PIL import Image

class HPMonitor:
    def __init__(self):
        self.last_hp = 0
        # 调整血条红色范围
        self.red_lower = np.array([0, 0, 180])  # BGR
        self.red_upper = np.array([60, 60, 255])  # BGR
        self.smooth_factor = 0.3
        
    async def get_hp(self, image):
        """获取血量数值"""
        try:
            # 检查图像是否为空
            if image is None:
                print("图像为空")
                return self.last_hp
                
            # 检查numpy数组是否为空
            if isinstance(image, np.ndarray):
                if image.size == 0 or not image.any():
                    print("空的numpy数组")
                    return self.last_hp
                img_bgr = image
            # 检查PIL图像
            elif isinstance(image, Image.Image):
                img_bgr = cv2.cvtColor(np.array(image), cv2.COLOR_RGB2BGR)
            else:
                print(f"不支持的图像类型: {type(image)}")
                return self.last_hp
                
            cv2.imwrite('debug_hp_bgr.png', img_bgr)
            
            # 创建红色掩码
            mask = cv2.inRange(img_bgr, self.red_lower, self.red_upper)
            cv2.imwrite('debug_hp_mask.png', mask)
            
            # 计算血量
            total_pixels = float(mask.size)
            red_pixels = float(np.count_nonzero(mask))
            
            print(f"总像素数: {total_pixels}, 红色像素数: {red_pixels}")
            
            if total_pixels > 0:
                current_hp = int((red_pixels / total_pixels) * 100)
                print(f"计算得到的血量: {current_hp}%")
                self.last_hp = int(self.last_hp * (1 - self.smooth_factor) + 
                                 current_hp * self.smooth_factor)
                print(f"平滑后的血量: {self.last_hp}%")
                return self.last_hp
                
            return self.last_hp
            
        except Exception as e:
            print(f"血量识别失败: {e}")
            import traceback
            print(f"错误堆栈: {traceback.format_exc()}")
            return self.last_hp